<!-- 事件日志 -->
<template>
  <!-- <div class="dashboard-editor-container"> -->
    <el-row style="background: #fff;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <!-- <el-tab-pane label="按日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计趋势"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="按分布比例资产统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按分布比例资产统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!-- <el-tab-pane label="按分区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按分区统计分析"/>
            </el-col>
          </el-tab-pane>
          
          <el-tab-pane label="按校区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按校区统计分析"/>
            </el-col>
          </el-tab-pane> -->
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <!-- <el-table-column label="所在分区" prop="PrimArea" width="150" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所在校区" show-overflow-tooltip prop="SchoolName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.SchoolName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.DeviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采集时间" show-overflow-tooltip prop="TransTime" align="left"></el-table-column>
          <el-table-column label="扩展盘使用率" show-overflow-tooltip prop="Percent" width="520px" align="left">
            <template slot-scope="{row}">
              <div class="coldiv hasprogress"><el-progress style="width:320px" :stroke-width="10" :percentage="row.Percent"></el-progress>{{ row.Used }} / {{ row.Total }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" show-overflow-tooltip width="120px" align="left" fixed="right" >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="changeModer(scope.row)">最近曲线</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
      <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="最近曲线"
      :visible.sync="logDialog"
      v-el-drag-dialog
      width="800px">
      <linechart :chartData="lineData"></linechart>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="logDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
      
    </el-row>
  <!-- </div> -->
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import linechart from "./components/linechart.vue"
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { formatBytes, parseTime, formatTime2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import transversechartVue from '../home/admin/components/transversechart.vue';
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart, linechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按分布比例资产统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      barchartData: {xAxis:[],series:[]},
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      pie5Data: [],
      lineData: {},
      tableData:[],
      searchform:{},
      options:{},
      searchobj: {},
      logDialog: false,
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        // {
        //   col: 8,
        //   label: "分区校区选择",
        //   prop:"SchoolName",
        //   element: "el-cascader",
        //   initValue: "",
        //   placeholder: "请选择校区",
        //   options:[],
        //   props:{emitPath: true, checkStrictly: true, lazy: true, lazyLoad: that.lazyLoad},
        //   events: {
        //     input(val) {
        //       that.searchform.SchoolName = val
        //     },
        //   },
        // },
        {
          col: 4,
          label: "最小使用率",
          prop:"MinPercent",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择使用率",
          options:[
            {label: '0%', value: 0},
            {label: '10%', value: 10},
            {label: '20%', value: 20},
            {label: '30%', value: 30},
            {label: '40%', value: 40},
            {label: '50%', value: 50},
            {label: '60%', value: 60},
            {label: '70%', value: 70},
            {label: '80%', value: 80},
            {label: '90%', value: 90},
          ],
          events: {
            input(val) {
              that.searchform.MinPercent = val
            },
          },
        },
        {
          col: 4,
          label: "最大使用率",
          prop:"MaxPercent",
          element: "el-select",
          initValue: 100,
          placeholder: "请选择使用率",
          options:[
            {label: '10%', value: 10},
            {label: '20%', value: 20},
            {label: '30%', value: 30},
            {label: '40%', value: 40},
            {label: '50%', value: 50},
            {label: '60%', value: 60},
            {label: '70%', value: 70},
            {label: '80%', value: 80},
            {label: '90%', value: 90},
            {label: '100%', value: 100},
          ],
          events: {
            input(val) {
              that.searchform.MaxPercent = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'MinPercent', 0)
    this.$set(this.searchform,'MaxPercent', 100)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.GetSchoolStatusSumTree()
  },
  methods: {
    // 获取子节点的校区
    async lazyLoad(node, resolve){
      if(node.level < 3){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SecondArea: node.label,
          }
        }
        const res = await connrequest('GetSchool', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
        })
        resolve(arr) 
      }
    },
    // 获取校区树
    async GetSchoolStatusSumTree() {
      const res = await connrequest('GetSchoolStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '分区校区选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
          }))
        }))
      }
    },
    handleChange(){},
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按分布比例资产统计分析':
          this.GetDeviceRealPerfStatusSumGroupByDevice()
          break;
        case '按分区统计分析':
          this.GetDeviceRealPerfStatusSumGroupByArea()
          break;
        case '按校区统计分析':
          this.GetDeviceRealPerfStatusSumGroupBySchool()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按分布比例资产统计分析'){
        let percent = val.split('%')[0] * 1
        this.searchobj = { MinPercent: percent, MaxPercent: percent + 10 }
        this.GetEventLog(this.searchobj)
      }else if(title === '按分区统计分析'){
        this.searchobj = { PrimArea: val.split('_')[0], SecondArea: val.split('_')[1] }
        this.GetEventLog(this.searchobj)
      }else if(title === '按校区统计分析'){
        this.searchobj = { SchoolName: val }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按分布比例资产统计分析':
          this.GetDeviceRealPerfStatusSumGroupByDevice()
          break;
        case '按分区统计分析':
          this.GetDeviceRealPerfStatusSumGroupByArea()
          break;
        case '按校区统计分析':
          this.GetDeviceRealPerfStatusSumGroupBySchool()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          PrimArea: this.searchform?.SchoolName?.[1] || '',
          SecondArea: this.searchform?.SchoolName?.[2] || '',
          SchoolName: this.searchform.SchoolName?.[3] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatus', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.Used = (item.Used / 1024).toFixed(2) + 'GB'
        item.Total = (item.Total / 1024).toFixed(2) + 'GB'
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 按分布比例资产统计分析
    async GetDeviceRealPerfStatusSumGroupByDevice(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          PrimArea: this.searchform?.SchoolName?.[1] || '',
          SecondArea: this.searchform?.SchoolName?.[2] || '',
          SchoolName: this.searchform.SchoolName?.[3] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatusSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: `${item.ClassID - 10}% ~ ${item.ClassID}%`, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 按分区统计分析
    async GetDeviceRealPerfStatusSumGroupByArea(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          PrimArea: this.searchform?.SchoolName?.[1] || '',
          SecondArea: this.searchform?.SchoolName?.[2] || '',
          SchoolName: this.searchform.SchoolName?.[3] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatusSumGroupByArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 按校区
    async GetDeviceRealPerfStatusSumGroupBySchool(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          PrimArea: this.searchform?.SchoolName?.[1] || '',
          SecondArea: this.searchform?.SchoolName?.[2] || '',
          SchoolName: this.searchform.SchoolName?.[3] || '',
          MinPercent: this.searchform.MinPercent,
          MaxPercent: this.searchform.MaxPercent,
          PerfType: 4,
        }
      }
      const res = await connrequest('GetDeviceRealPerfStatusSumGroupBySchool', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie3Data = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "最小使用率"){
          item.initValue = 0
        }else if(item.label === "最大使用率"){
          item.initValue = 100
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'MinPercent', 0)
      this.$set(this.searchform,'MaxPercent', 100)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    async changeModer(row){
      const data = {
        Filter:{
          PerfType: 4,
          DeviceID: row.DeviceID
        }
      }
      const res = await connrequest('GetDeviceHistoryPerfStatus', data)
      let downByte = []
      let time = []
      res.Data.map(item => {
        downByte.push(item.Percent)
        time.push(parseTime(item.TransTime))
      })
      this.lineData = {time, downByte}
      this.logDialog = true
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>